import { reqShopCartList, reqDeleteGoods, reqCheckedGoods } from '@/api'
import { SHOPCART_LIST } from '@/store/mutation-types'

export default {
  namespaced: true,
  state: {
    shopCartList: []
  },
  actions: {
    //获取购物车商品列表
    async getShopCartList({ commit }) {
      const res = await reqShopCartList()
      if (res.code == 200) {
        commit(SHOPCART_LIST, res.data)
      } else {
        console.log('shopcaet仓库获取shopCartList失败');
      }
    },
    //删除购物车单件商品
    async deleteGoods(_, goodsId) {
      try {
        const res = await reqDeleteGoods(goodsId)
        if (res.code == 200) {
          return Promise.resolve(true)
        }
      } catch (error) {
        return Promise.reject(false)
      }

    },
    //修改购物车商品的选中状态
    async checkedGoods(_, { goodsId, isChecked }) {
      try {
        const res = await reqCheckedGoods(goodsId, Number(isChecked))
        if (res.code == 200) {
          return Promise.resolve(true)
        }
      } catch (error) {
        return Promise.reject(false)
      }

    },
    //删除购物车选中的所有商品
    delAllChecked({ dispatch, state }) {
      if (state.shopCartList[0]) {
        const promiseAll = []
        state.shopCartList[0].cartInfoList.forEach((item) => {
          if (item.isChecked == 1) {
            const res = dispatch("deleteGoods", item.skuId);
            promiseAll.push(res)
          }
        });
        return Promise.all(promiseAll)
      }

    },
    //全选按钮
    changeAllChecked({ dispatch, state }, checked) {
      if (state.shopCartList[0]) {
        const promiseAll = []
        state.shopCartList[0].cartInfoList.forEach((item) => {
          if (item.isChecked != checked) {
            const res = dispatch("checkedGoods", {
              goodsId: item.skuId,
              isChecked: checked,
            });
            promiseAll.push(res)
          }
        });
        return Promise.all(promiseAll);
      }
    }
  },
  mutations: {
    [SHOPCART_LIST]: (context, data) => context.shopCartList = data
  },
  getters: {
    cartInfoList(state) {
      if (state.shopCartList.length >= 1) {
        return state.shopCartList[0].cartInfoList || []
      }
    }
  },
}